from PyQt5.QtCore import Qt, QAbstractTableModel, QModelIndex
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView, QVBoxLayout, QWidget

class CustomTableModel(QAbstractTableModel):
    def __init__(self, data, headers):
        super().__init__()
        self._data = data
        self._headers = headers

    def rowCount(self, parent=QModelIndex()):
        return len(self._data)

    def columnCount(self, parent=QModelIndex()):
        return len(self._headers)

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            return self._data[index.row()][index.column()]
        return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            return self._headers[section]
        return None

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建一个 QTableView
        self.tableView = QTableView()

        # 创建自定义模型并设置数据
        data = [
            ['Item 1-1', 'Item 1-2', 'Item 1-3'],
            ['Item 2-1', 'Item 2-2', 'Item 2-3'],
            ['Item 3-1', 'Item 3-2', 'Item 3-3'],
            ['Item 4-1', 'Item 4-2', 'Item 4-3'],
            ['Item 5-1', 'Item 5-2', 'Item 5-3']
        ]
        headers = ['Column 1', 'Column 2', 'Column 3']
        self.model = CustomTableModel(data, headers)
        self.tableView.setModel(self.model)

        # 设置窗口布局
        layout = QVBoxLayout()
        layout.addWidget(self.tableView)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        self.setWindowTitle("QTableView Example")
        self.resize(400, 300)

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()
